<template>
  <view class="detail-container">
    <!-- 顶部操作栏 -->
    <view class="action-bar">
      <uni-icons type="arrowleft" size="24" color="#5c3c1c" @click="goBack" />
      <text class="title">商品详情</text>
      <uni-icons type="more-filled" size="24" color="#5c3c1c" @click="showActionSheet" />
    </view>
    
    <!-- 商品信息展示 -->
    <scroll-view 
      scroll-y 
      class="detail-scroll"
      :scroll-top="scrollPosition"
      @scroll="handleScroll"
      ref="scrollContainer"
    >
      <!-- 商品图片 -->
      <image 
        :src="furniture.imageUrl" 
        mode="aspectFit" 
        class="product-image"
      />
      
      <!-- 商品基本信息 -->
      <view class="info-card">
        <text class="product-name">{{ furniture.name }}</text>
        
        <view class="price-section">
          <text class="price">¥{{ furniture.price }}</text>
          <text class="original-price" v-if="furniture.originalPrice">
            ¥{{ furniture.originalPrice }}
          </text>
        </view>
        
        <view class="meta-info">
          <text class="meta-item">分类：{{ furniture.category }}</text>
          <text class="meta-item">材质：{{ furniture.material }}</text>
          <text class="meta-item">状态：{{ furniture.status ? '上架中' : '已下架' }}</text>
        </view>
      </view>
      
      <!-- 商品描述 -->
      <view class="description-card">
        <text class="section-title">商品描述</text>
        <text class="description-text">{{ furniture.description || '暂无描述' }}</text>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="edit-btn" @click="navigateToEdit">编辑商品</button>
        <button class="delete-btn" @click="confirmDelete">删除商品</button>
      </view>
    </scroll-view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <uni-icons type="spinner-cycle" size="40" color="#8B4513" class="spinner" />
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 错误提示 -->
    <view v-if="error" class="error-overlay">
      <uni-icons type="close-circle" size="40" color="#e64340" />
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="retryLoad">重试</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      furniture: {
        name: '',
        price: '',
        imageUrl: '',
        category: '',
        material: '',
        description: '',
        status: true
      },
      loading: true,
      error: null,
      scrollPosition: 0
    }
  },
  onLoad(options) {
    if (!options.id) {
      this.error = '未获取到商品ID';
      this.loading = false;
      return;
    }
    
    this.loadDetail(options.id);
  },
  onReady() {
    // 确保DOM渲染完成后再尝试恢复滚动位置
    setTimeout(() => {
      this.restoreScrollPosition();
    }, 300);
  },
  methods: {
    async loadDetail(id) {
      this.loading = true;
      this.error = null;
      
      try {
        // 从本地存储获取所有家具数据
        const furnitureData = uni.getStorageSync('furniture_data') || [];
        
        // 根据ID查找商品
        const furniture = furnitureData.find(item => item._id === id);
        
        if (furniture) {
          this.furniture = furniture;
          console.log('商品详情加载成功:', furniture);
        } else {
          this.error = '未找到商品信息';
        }
      } catch (e) {
        console.error('加载商品详情失败:', e);
        this.error = '加载商品详情失败，请重试';
      } finally {
        this.loading = false;
      }
    },
    
    retryLoad() {
      // 重新加载当前页
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const options = currentPage.options;
      
      if (options.id) {
        this.loadDetail(options.id);
      }
    },
    
    handleScroll(e) {
      // 保存滚动位置
      this.scrollPosition = e.detail.scrollTop;
    },
    
    restoreScrollPosition() {
      // 安全恢复滚动位置
      try {
        if (this.$refs.scrollContainer && this.scrollPosition > 0) {
          this.$refs.scrollContainer.scrollTo({
            top: this.scrollPosition,
            duration: 0
          });
        }
      } catch (e) {
        console.warn('恢复滚动位置失败:', e);
      }
    },
    
    goBack() {
      uni.navigateBack();
    },
    
    showActionSheet() {
      uni.showActionSheet({
        itemList: ['分享', '收藏', '举报'],
        success: (res) => {
          console.log('操作:', res.tapIndex);
        }
      });
    },
    
    navigateToEdit() {
      if (this.furniture._id) {
        uni.navigateTo({
          url: `/pages/furniture/edit?id=${this.furniture._id}`
        });
      } else {
        uni.showToast({
          title: '无法编辑，商品信息不完整',
          icon: 'none'
        });
      }
    },
    
    confirmDelete() {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除 "${this.furniture.name}" 吗？`,
        success: (res) => {
          if (res.confirm) {
            this.deleteFurniture();
          }
        }
      });
    },
    
    async deleteFurniture() {
      try {
        // 从本地存储获取所有家具数据
        let furnitureData = uni.getStorageSync('furniture_data') || [];
        
        // 过滤掉当前商品
        furnitureData = furnitureData.filter(item => item._id !== this.furniture._id);
        
        // 保存更新后的数据
        uni.setStorageSync('furniture_data', furnitureData);
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 1秒后返回
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      } catch (e) {
        console.error('删除商品失败:', e);
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style scoped>
.detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f3ed;
  position: relative;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 30rpx;
  background-color: white;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.title {
  font-size: 34rpx;
  font-weight: bold;
  color: #5c3c1c;
}

.detail-scroll {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
}

.product-image {
  width: 100%;
  height: 400rpx;
  border-radius: 16rpx;
  background-color: #f5f5f5;
  margin-bottom: 30rpx;
}

.info-card {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.product-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 25rpx;
}

.price {
  font-size: 40rpx;
  color: #d42828;
  font-weight: bold;
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 15rpx;
}

.meta-info {
  display: flex;
  flex-direction: column;
}

.meta-item {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.description-card {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #5c3c1c;
  margin-bottom: 20rpx;
  display: block;
}

.description-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.edit-btn, .delete-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  font-size: 30rpx;
}

.edit-btn {
  background-color: #5c3c1c;
  color: white;
}

.delete-btn {
  background-color: #d42828;
  color: white;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.spinner {
  animation: rotate 1s linear infinite;
}

.loading-text {
  font-size: 32rpx;
  color: #5c3c1c;
  margin-top: 20rpx;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 错误状态 */
.error-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 100;
  padding: 40rpx;
}

.error-text {
  font-size: 32rpx;
  color: #e64340;
  margin: 20rpx 0;
  text-align: center;
}

.retry-btn {
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  background-color: #5c3c1c;
  color: white;
  border-radius: 35rpx;
  font-size: 28rpx;
  margin-top: 30rpx;
}
</style>